<?php
$pay_success = FALSE;
$pp_errors = array();
// Handle payment submit, if any
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['submitpayment'])) {
	$pp_errors = validatePost();
	
	$amount = PP_amount();
	
	// Attempt to process, if no errors
	if (count($pp_errors) == 0) {
		// CALLER SERVICE
		define('USE_PROXY',FALSE);
		define('VERSION', '3.0'); // REQUIRED
		
		$pp_opts = $dl_paypalpro->getAdminOptions();

		$API_UserName = $pp_opts['api_username'];
		$API_Password = $pp_opts['api_password'];
		$API_Signature = $pp_opts['api_signature'];
		$API_Endpoint = $pp_opts['api_endpoint'];
		$version=VERSION;
		
		/**
		  * hash_call: Function to perform the API call to PayPal using API signature
		  * @methodName is name of API  method.
		  * @nvpStr is nvp string.
		  * returns an associtive array containing the response from the server.
		*/

		function hash_call($methodName,$nvpStr) {
			//declaring of global variables
			global $API_Endpoint,$version,$API_UserName,$API_Password,$API_Signature,$nvp_Header,$pp_errors;
		
			//setting the curl parameters.
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
		
			//turning off the server and peer verification(TrustManager Concept).
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		
			curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
			curl_setopt($ch, CURLOPT_POST, 1);
			//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
		   //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php 
			if(USE_PROXY)
			curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT); 
		
			//NVPRequest for submitting to server
			$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($version)."&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature).$nvpStr;
		
			//setting the nvpreq as POST FIELD to curl
			curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
		
			//getting response from server
			$response = curl_exec($ch);
		
			//convrting NVPResponse to an Associative Array
			$nvpResArray=deformatNVP($response);
			$nvpReqArray=deformatNVP($nvpreq);
			$_SESSION['nvpReqArray']=$nvpReqArray;
		
			if (curl_errno($ch)) {
				// moving to display page to display curl errors
				$_SESSION['curl_error_no']=curl_errno($ch) ;
				$_SESSION['curl_error_msg']=curl_error($ch);
				$pp_errors[] = curl_error($ch);
			} else {
				//closing the curl
				curl_close($ch);
			}
		
			return $nvpResArray;
		}

		/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
		  * It is usefull to search for a particular key and displaying arrays.
		  * @nvpstr is NVPString.
		  * @nvpArray is Associative Array.
		  */
		
		function deformatNVP($nvpstr) {
			$intial=0;
			$nvpArray = array();
		
			while(strlen($nvpstr)){
				//postion of Key
				$keypos= strpos($nvpstr,'=');
				//position of value
				$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
		
				/*getting the Key and Value values and storing in a Associative Array*/
				$keyval=substr($nvpstr,$intial,$keypos);
				$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
				//decoding the respose
				$nvpArray[urldecode($keyval)] =urldecode( $valval);
				$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
			}
			return $nvpArray;
		}
	
		// Attempt transaction...
		// Get required parameters from the web form for the request
		$paymentType =urlencode('Sale');
		
		// cc_type. one of Visa MasterCard Discover Amex
		if ($cc_type == 4) {
			$creditCardType = urlencode("Amex");
		} else {
			$creditCardType = urlencode($credit_cards[$cc_type]);
		}
		
		$creditCardNumber = urlencode($cc_num);
		$cvv2Number = urlencode($cc_cvc);

		$firstName =urlencode($fname);
		$lastName =urlencode($lname);
		$Baddress = urlencode($address1);
		$Bcity = urlencode($city);
		$Bstate =urlencode($state);
		$Bzip = urlencode($zip);
		
		$Bamount = urlencode(number_format($amount,2,'.',''));

		$currencyCode="USD";

		/* Construct the request string that will be sent to PayPal.

		   The variable $nvpstr contains all the variables and is a

		   name value pair string with & as a delimiter */

		$nvpstr="&PAYMENTACTION=$paymentType&AMT=$Bamount&CREDITCARDTYPE=$creditCardType";
		$nvpstr .= "&ACCT=$creditCardNumber&EXPDATE=". $cc_exp ."&CVV2=$cvv2Number";
		$nvpstr .= "&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$Baddress&CITY=$Bcity&STATE=$Bstate";
		$nvpstr .= "&ZIP=$Bzip&COUNTRYCODE=$country&CURRENCYCODE=$currencyCode";
		
		// Add IP ADDRESS
		$nvpstr .= "&IPADDRESS=".urlencode($_SERVER['REMOTE_ADDR']);
///die($nvpstr);
		// Make the API call to PayPal, using API signature.
		// The API response is stored in an associative array called $resArray

		$resArray = hash_call("doDirectPayment",$nvpstr);


		$ack = strtoupper($resArray["ACK"]);

		if(trim($ack)=="SUCCESS") {
			$_SESSION['TxnID'] = $resArray["TRANSACTIONID"];
			
			// Send thank you email address/receipt
			$p_date = date("M d, Y");
			
			$subject = $pp_opts['email_subject'];
			$message = "Thank you for your payment.
			
The details of your payment are as follows:

Payment from $fname $lname
Payment Date: $p_date
Payment Amount: \$$Bamount

Thank You!

";
			$headers = "From: ".$pp_opts['email_from']."\r\n";
			$headers .= "Return-Path: ".$pp_opts['email_from']."\r\n";
			
			mail($eaddr, $subject, $message, $headers);
			
			if (validEmail($pp_opts['notification_email_addr'])) {
				mail($pp_opts['notification_email_addr'], $subject, $message, $headers);
			}
		
			$pay_success = TRUE;
		} else {
			$PayStatus = 0;
			$err_msg = $resArray["L_LONGMESSAGE0"];
			
			// Remove 'and type' from message
			$err_msg = str_replace(' and type','', $err_msg);
			
			$pp_errors[] = $err_msg;
		}	
	}
}
?>